package com.lzs.bootsafety.business.sys.controller;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageInfo;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.lzs.bootsafety.business.sys.entity.SysUser;
import com.lzs.bootsafety.business.sys.entity.SysUserPwd;
import com.lzs.bootsafety.common.base.controller.BaseController;
import com.lzs.bootsafety.common.base.mapper.Insert;
import com.lzs.bootsafety.common.util.PasswordMakeUtil;
import com.lzs.bootsafety.common.util.Resu;
import com.lzs.bootsafety.common.util.annotation.OperLog;
import com.lzs.bootsafety.common.util.easyexcel.ExcelUtil;
import com.lzs.bootsafety.common.util.enums.OperType;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.thymeleaf.util.ArrayUtils;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Date;

/**
 * @author  zhanshi Liu
 * @date    2020/03/22
 * @website www.jhmsona.cn
 */
@Controller
@RequestMapping("/sys/user")
public class UserController extends BaseController {
    //用户登录
    @PostMapping("/login")
    @ResponseBody
    @OperLog(operModule = "用户管理",operType = OperType.SELECT,isSaveReqParams = false,isLogin = true)
    public Object login(@Valid String username, @Valid String password, String verifyCode) {
        UsernamePasswordToken token = new UsernamePasswordToken(username,password);
        Subject subject = SecurityUtils.getSubject();
        String verCode = (String) subject.getSession().getAttribute(SHIRO_VERIFY_SESSION);
        if("".equals(verifyCode)||(!verCode.equals(verifyCode))) {
            return Resu.error("验证码不正确");
        }
        try {
            subject.login(token);
        }catch (IncorrectCredentialsException ice){
            return Resu.error("密码不正确");
        }catch(UnknownAccountException uae){
            return Resu.error("账号不存在");
        }catch(AuthenticationException ae){
            return Resu.error("状态不正常");
        }
        if(subject.isAuthenticated()) {
            return Resu.suces("登录成功");
        }else {
            token.clear();
            return Resu.error("登录失败");
        }
    }
    @Autowired
    private DefaultKaptcha defaultKaptcha;
    private String SHIRO_VERIFY_SESSION = "verifySessionCode";
    @GetMapping("/getCode")
    public void getCode(HttpServletResponse response, HttpServletRequest request) throws IOException {
        byte[] verByte = null;
        ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();
        try {
            //生产验证码字符串并保存到session中
            String createText = defaultKaptcha.createText();
            request.getSession().setAttribute(SHIRO_VERIFY_SESSION,createText);
            //使用生产的验证码字符串返回一个BufferedImage对象并转为byte写入到byte数组中
            BufferedImage challenge = defaultKaptcha.createImage(createText);
            ImageIO.write(challenge,"jpg",jpegOutputStream);
        } catch (IllegalArgumentException e){
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        } catch (IOException e){
            e.printStackTrace();
        }
        //定义response输出类型为image/jpeg类型，使用response输出流输出图片的byte数组
        verByte = jpegOutputStream.toByteArray();
        response.setHeader("Cache-Control", "no-store");
        response.setHeader("Pragma", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setContentType("image/jpeg");
        ServletOutputStream responseOutputStream = response.getOutputStream();
        responseOutputStream.write(verByte);
        responseOutputStream.flush();
        responseOutputStream.close();
    }
    @GetMapping("/getUserByWhere")
    @ResponseBody
    @RequiresPermissions("sys:user:list")
    public Resu getUserByWhere(@RequestParam("data") String data){
        SysUser sysUser = JSON.parseObject(data,SysUser.class);
        PageInfo<SysUser> pageInfo = sysUserService.getUserByWhere(sysUser);
        return Resu.page(pageInfo.getList(),pageInfo.getTotal(),200);
    }
    @PostMapping("/addSysUser")
    @ResponseBody
    @RequiresPermissions("sys:user:add")
    public Resu addSysUser(@Validated({Insert.class})@RequestBody SysUser sysUser, BindingResult bindingResult){
        if (bindingResult.getErrorCount() > 0){
            String verifyResult = validateResult(bindingResult);
            return Resu.error(verifyResult);
        }
        if (!StringUtils.isEmpty(sysUserService.getUserByName(sysUser.getUsername()))){
            return Resu.error("用户名已存在，添加失败");
        } else if (!StringUtils.isEmpty(sysUserService.checkUserByEmail(sysUser.getEmail()))){
            return Resu.error("邮箱已存在，添加失败");
        } else if (!StringUtils.isEmpty(sysUserService.checkUserByMobile(sysUser.getMobile()))){
            return Resu.error("手机号已存在，添加失败");
        }
        sysUser.setSalt(Long.toString(System.currentTimeMillis()));
        sysUser.setPassword(PasswordMakeUtil.getPassword(sysUser.getPassword(),sysUser.getSalt(),8));
        sysUser.setCreatePeople(getUserName());
        sysUser.setCreateTime(new Date());
        return respAdd(sysUserService.addSysUser(sysUser));
    }
    @DeleteMapping("/del")
    @ResponseBody
    @RequiresPermissions("sys:user:del")
    public Resu del(Long[] ids){
        if(ArrayUtils.contains(ids, getUserId())){
            return Resu.error("不能删除当前登录用户");
        }
        return respDel(sysUserService.del(ids));
    }
    @PutMapping("/modify")
    @ResponseBody
    @RequiresPermissions("sys:user:modify")
    public Resu modify(@RequestParam String  data){
        SysUser sysUser = JSON.parseObject(data,SysUser.class);
        sysUser.setUpdatePeople(getUserName());
        sysUser.setUpdateTime(new Date());
        return respudp(sysUserService.updateByPrimaryKeySelective(sysUser));
    }
    @PutMapping("/modifyPwd")
    @ResponseBody
    public Resu modifyPwd(@RequestBody SysUserPwd sysUserPwd){
        sysUserPwd.setUserId(getUserId());
        int r = sysUserService.modifyPassword(sysUserPwd);
        return respudp(r);
    }
    @GetMapping("/getUserByUserId")
    @ResponseBody
    @RequiresPermissions("sys:user:info")
    public Resu get(Long userId){
        Resu  resu = Resu.suces();
        resu.put("role",sysRoleService.getRoleList());
        resu.put("post",sysPostService.getPostList());
        if (!StringUtils.isEmpty(userId)){
            resu.put("data",sysUserService.getByPrimaryKey(userId));
            resu.put("roleIds",sysRoleService.getRolesByUserId(userId));
            resu.put("postIds",sysPostService.getPostIdsByUserId(userId));
        }
        return resu;
    }
    @GetMapping("/export")
    @ResponseBody
    @RequiresPermissions("sys:user:export")
    public void export(Long[] userIds,HttpServletResponse response) throws IOException {
        ExcelUtil<SysUser> writeExcel = new ExcelUtil<SysUser>();
        if(!StringUtils.isEmpty(userIds)){
              writeExcel.write(response,sysUserService.getUserByUserId(userIds));
        }else{
              writeExcel.write(response,sysUserService.getAllUser());
        }
    }

}


